﻿using System;
using System.Buffers;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace PipeSockets
{
    public class TcpClient
    {
        private Socket _socket;
        private TcpConnection _connection;
        private EndPoint _remoteEndPoint;
        private IProtocolParser _parser;
        public Action<AbstractConnection, ReadOnlySequence<byte>> MessageReceived;
        public TcpClient(EndPoint remoteEndPoint, IProtocolParser parser, Action<AbstractConnection, ReadOnlySequence<byte>> onReceived)
        {
            _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _parser = parser;
            _remoteEndPoint = remoteEndPoint;
            MessageReceived = onReceived;
        }
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            await _socket.ConnectAsync(_remoteEndPoint, cancellationToken);
            _connection = new TcpConnection(_socket, _parser, MessageReceived, null, null);
            await _connection.StartAsync(cancellationToken);
        }

        public async Task SendAsync(byte[] bytes)
        {
            await _connection.SendFrameAsync(bytes);
        }

        public async Task StopAsync(CancellationToken cancellationToken)
        {
            await _connection.StopAsync(cancellationToken);
        }
    }
}
